<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<%@ include file="../common.jsp"%>
<%@ page import="org.springside.core.Constants,cn.firstsoft.firstframe.admin.*"%>
<%@ page import="java.io.*,java.util.*,org.jdom.*,org.jdom.input.*,org.jdom.output.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<%
	String action = request.getParameter("action");
	if (action == null) action = "new";
	String id = "";
	String name = "";
	String dbname = "";
	String dbtype = "";
	String datasource = "";
	String dbuser = "";
	String dbpassword = "";
	String maindir = "";
	int error_code = 0;

	if ("save".equals(action)) {
		id = request.getParameter("id");
		if (id == null) id = "";
		name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
		if (name == null) name = "";
		dbname = request.getParameter("dbname");
		if (dbname == null) dbname ="";
		dbtype = request.getParameter("dbtype");
		if (dbtype == null) dbtype = "";
		datasource = request.getParameter("datasource");
		if (datasource == null) datasource = "";
		dbuser = request.getParameter("dbuser");
		if (dbuser == null) dbuser = "";
		dbpassword = request.getParameter("dbpassword");
		if (dbpassword == null) dbpassword = "";
		maindir = request.getParameter("maindir");
		if (maindir == null) maindir = "";
		
		//校验，合法性检查，根据安装类型和应用服务器类型判断
		String xmlFile = "";
		if ("TOMCAT".equals(Environment.getWebServerName())) { 
			xmlFile = Environment.getWebServerPath() + File.separator + "conf" + File.separator + "server.xml";
		} else if ("APUSIC".equals(Environment.getWebServerName())) {
			xmlFile = Environment.getWebServerPath() + File.separator + "config" + File.separator + "datasources.xml";
		} else {
			xmlFile = "unknown";
		}	
		System.out.println(xmlFile);	
		File file = new File(xmlFile);
		
		if (file.exists()) {
			SAXBuilder builder = new SAXBuilder();
			Document doc;
			try {
				if ("TOMCAT".equals(Environment.getWebServerName())) { 
					doc = builder.build(file);
					Element server = doc.getRootElement();
					Element service = server.getChild("Service");
					Element engine = service.getChild("Engine");
					Element host = engine.getChild("Host");
					Element context = host.getChild("Context");
					List resourceList = context.getChildren("Resource");
					
					for (int i=0; i<resourceList.size(); i++) {
						Element resource = (Element)resourceList.get(i);
						//判断是否已经有这个名字了
						String jndi_name = resource.getAttributeValue("name");
						
						if (jndi_name.equalsIgnoreCase("jdbc/"+id)) {
							//错误编号1，这个数据源名字已经被用了


							error_code = 1;
							break;
						}
					}
				} else if ("APUSIC".equals(Environment.getWebServerName())) {
					doc = builder.build(file);
					Element datasources = doc.getRootElement();
					List resourceList = datasources.getChildren("datasource");
				
					for (int i=0; i<resourceList.size(); i++) {
						Element resource = (Element)resourceList.get(i);	
						String jndi_name = resource.getAttributeValue("jndi-name");
						
						if (jndi_name.equalsIgnoreCase("jdbc/"+id)) {
							//错误编号1，这个数据源名字已经被用了


							error_code = 1;
							break;
						}	
					}									
				} else {
					//什么也不做
				}
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			//错误编号2，目标文件不存在
			error_code = 2;
		}

		String datacenterXmlFile = System.getProperty("oa_application.config") + File.separator + "datacenter.xml";
		File datacenterFile = new File(datacenterXmlFile);
		
		//所有的检查都通过的情况下
		if (error_code == 0) {
			//保存到应用服务器的数据源
			SAXBuilder builder1 = new SAXBuilder();
			Document doc1;
			Document dcdoc;
			try {
				if ("TOMCAT".equals(Environment.getWebServerName())) { 
					doc1 = builder1.build(file);
					Element server = doc1.getRootElement();
					Element service = server.getChild("Service");
					Element engine = service.getChild("Engine");
					Element host = engine.getChild("Host");
					Element context = host.getChild("Context");
					
					Element resource = new Element("Resource");
					//  <Resource name="jdbc/EasDS" auth="Container" type="javax.sql.DataSource"
	                //maxActive="100" maxIdle="30" maxWait="10000"
	                //username="sa" password="sa" driverClassName="net.sourceforge.jtds.jdbc.Driver"
	                //url="jdbc:jtds:sqlserver://localhost:1433;DatabaseName=eas530"/>
					resource.setAttribute("name", "jdbc/" + id);
					resource.setAttribute("auth", "Container");
					resource.setAttribute("type", "javax.sql.DataSource");
					resource.setAttribute("maxActive", "100");
					resource.setAttribute("maxIdle", "30");
					resource.setAttribute("maxWait", "10000");
					resource.setAttribute("username", dbuser);
					resource.setAttribute("password", dbpassword);
					if ("sqlserver".equals(dbtype)) {
						resource.setAttribute("driverClassName", "net.sourceforge.jtds.jdbc.Driver");
						resource.setAttribute("url", "jdbc:jtds:sqlserver://" + datasource + ";DatabaseName=" + dbname);
					} else if ("oracle".equals(dbtype)) {
						resource.setAttribute("driverClassName", "oracle.jdbc.OracleDriver");
						resource.setAttribute("url", "jdbc:oracle:thin:@"+ datasource + ":" + dbname);
					}
									
					context.addContent(resource);
					XMLOutputter outp = new XMLOutputter();
					outp.setFormat(Format.getPrettyFormat());
					outp.output(doc1, new FileOutputStream(file));	
				} else if ("APUSIC".equals(Environment.getWebServerName())) {
					doc1 = builder1.build(file);
					
					Element datasources = doc1.getRootElement();
					
					Element resource = new Element("datasource");

					resource.setAttribute("name", id);
					resource.setAttribute("jndi-name", "jdbc/" + id);
					resource.setAttribute("idle-timeout", "60");
					resource.setAttribute("min-spare-connections", "50");
					resource.setAttribute("max-spare-connections", "50");
					resource.setAttribute("max-connections", "80");
					
					Element property1 = new Element("property");
					property1.setAttribute("name", "user");
					property1.setAttribute("value", dbuser);
					Element property2 = new Element("property");
					property2.setAttribute("name", "password");
					property2.setAttribute("value", dbpassword);
					Element property3 = new Element("property");
					property3.setAttribute("name","test-before-reused");
					property3.setAttribute("value", "true");
					Element property4 = new Element("property");
					property4.setAttribute("name", "test-command");

					if ("sqlserver".equals(dbtype)) {
						resource.setAttribute("driver-class", "net.sourceforge.jtds.jdbc.Driver");
						resource.setAttribute("url", "jdbc:jtds:sqlserver://" + datasource + ";DatabaseName=" + dbname);
						property4.setAttribute("value", "select 1");
					} else if ("oracle".equals(dbtype)) {
						resource.setAttribute("driver-class", "oracle.jdbc.OracleDriver");
						resource.setAttribute("url", "jdbc:oracle:thin:@"+ datasource + ":" + dbname);
						property4.setAttribute("value", "SELECT 1 FROM DUAL");
					}
					resource.addContent(property1);
					resource.addContent(property2);
					resource.addContent(property3);
					resource.addContent(property4);
									
					datasources.addContent(resource);
					
					XMLOutputter outp = new XMLOutputter();
					outp.setFormat(Format.getPrettyFormat());
					outp.output(doc1, new FileOutputStream(file));				
				} else {
					//其他应用服务器


				}			
				
				dcdoc = builder1.build(datacenterFile);
				Element datacenters = dcdoc.getRootElement();
				
				Element datacenter = new Element("datacenter");
				datacenter.setAttribute("id", id);
				datacenter.setAttribute("name", name);
				datacenter.setAttribute("dbname", dbname);
				datacenter.setAttribute("dbtype", dbtype);
				if ("sqlserver".equals(dbtype)) {
					datacenter.setAttribute("dbversion", "JTDS");
				} else if ("oracle".equals(dbtype)) {
					datacenter.setAttribute("dbversion", "ORACLE");
				}
				datacenter.setAttribute("datasource", datasource);
				datacenter.setAttribute("dbuser", dbuser);
				
				datacenter.setAttribute("dbpassword", dbpassword);
				datacenter.setAttribute("maindir", maindir);
				//通过jdbc.properties来判断，是否已经正在使用
				datacenter.setAttribute("isdeploy", "false");
				
				datacenters.addContent(datacenter);	
							
				XMLOutputter outp1 = new XMLOutputter();
				Format format = Format.getPrettyFormat();
				format.setEncoding("UTF-8");
				outp1.setFormat(format);
				outp1.output(dcdoc, new FileOutputStream(datacenterFile));					
				
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

			//保存到datacenter.xml文件中


		}
	} else if ("update".equals(action)) {
		//将修改设置，首先找到数据源中的设置，然后对属性进行修改，然后保存
		id = request.getParameter("id");
		if (id == null) id = "";
		name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
		if (name == null) name = "";
		dbname = request.getParameter("dbname");
		if (dbname == null) dbname ="";
		dbtype = request.getParameter("dbtype");
		if (dbtype == null) dbtype = "";
		datasource = request.getParameter("datasource");
		if (datasource == null) datasource = "";
		dbuser = request.getParameter("dbuser");
		if (dbuser == null) dbuser = "";
		dbpassword = request.getParameter("dbpassword");
		if (dbpassword == null) dbpassword = "";
		maindir = request.getParameter("maindir");
		if (maindir == null) maindir = "";
		//校验，合法性检查，根据安装类型和应用服务器类型判断
		String xmlFile = "";
		if ("TOMCAT".equals(Environment.getWebServerName())) { 
			xmlFile = Environment.getWebServerPath() + File.separator + "conf" + File.separator + "server.xml";
		} else if ("APUSIC".equals(Environment.getWebServerName())) {
			xmlFile = Environment.getWebServerPath() + File.separator + "config" + File.separator + "datasources.xml";
		} else {
			xmlFile = "unknown";
		}	
		File file = new File(xmlFile);		
		
		String datacenterXmlFile = System.getProperty("oa_application.config") + File.separator + "datacenter.xml";
		File datacenterFile = new File(datacenterXmlFile);		

		//保存到应用服务器的数据源
		SAXBuilder builder1 = new SAXBuilder();
		Document doc1;
		Document dcdoc;
		try {
			if ("TOMCAT".equals(Environment.getWebServerName())) { 
				doc1 = builder1.build(file);
				Element server = doc1.getRootElement();
				Element service = server.getChild("Service");
				Element engine = service.getChild("Engine");
				Element host = engine.getChild("Host");
				Element context = host.getChild("Context");
				List resourceList = context.getChildren("Resource");
				for (int i=0; i<resourceList.size(); i++) {
					Element resource = (Element)resourceList.get(i);
					//如果tomcat
					if (("jdbc/"+id).equals(resource.getAttributeValue("name"))) {
						resource.setAttribute("auth", "Container");
						resource.setAttribute("type", "javax.sql.DataSource");
						resource.setAttribute("maxActive", "100");
						resource.setAttribute("maxIdle", "30");
						resource.setAttribute("maxWait", "10000");
						resource.setAttribute("username", dbuser);
						resource.setAttribute("password", dbpassword);
						if ("sqlserver".equals(dbtype)) {
							resource.setAttribute("driverClassName", "net.sourceforge.jtds.jdbc.Driver");
							resource.setAttribute("url", "jdbc:jtds:sqlserver://" + datasource + ";DatabaseName=" + dbname);
						} else if ("oracle".equals(dbtype)) {
							resource.setAttribute("driverClassName", "oracle.jdbc.OracleDriver");
							resource.setAttribute("url", "jdbc:oracle:thin:@"+ datasource + ":" + dbname);
						}
						break;
					}
				}
				
				XMLOutputter outp = new XMLOutputter();
				outp.setFormat(Format.getPrettyFormat());
				outp.output(doc1, new FileOutputStream(file));	
			} else if ("APUSIC".equals(Environment.getWebServerName())) {
				doc1 = builder1.build(file);
				Element datasources = doc1.getRootElement();
				List resourceList = datasources.getChildren("datasource");
				for (int i=0; i<resourceList.size(); i++) {
					Element resource = (Element)resourceList.get(i);				
					if (("jdbc/"+id).equals(resource.getAttributeValue("jndi-name"))) {
						List propertyList = resource.getChildren("property");
						for (int j=0; j<propertyList.size(); j++) {
							Element property = (Element)propertyList.get(j);
							if ("user".equals(property.getAttributeValue("name"))) {
								property.setAttribute("value", dbuser);
							}
							if ("password".equals(property.getAttributeValue("name"))) {
								property.setAttribute("value", dbpassword);
							}
						}
						if ("sqlserver".equals(dbtype)) {
							resource.setAttribute("driver-class", "net.sourceforge.jtds.jdbc.Driver");
							resource.setAttribute("url", "jdbc:jtds:sqlserver://" + datasource + ";DatabaseName=" + dbname);
						} else if ("oracle".equals(dbtype)) {
							resource.setAttribute("driver-class", "oracle.jdbc.OracleDriver");
							resource.setAttribute("url", "jdbc:oracle:thin:@"+ datasource + ":" + dbname);
						}
					}
				}
				XMLOutputter outp = new XMLOutputter();
				outp.setFormat(Format.getPrettyFormat());
				outp.output(doc1, new FileOutputStream(file));				
			} else {
				//其他应用服务器


			}						
			
			dcdoc = builder1.build(datacenterFile);
			Element datacenters = dcdoc.getRootElement();
			
			List datacenterList = datacenters.getChildren("datacenter");
			
			for (int i=0; i<datacenterList.size(); i++) {
				Element datacenter = (Element)datacenterList.get(i);
				if (id.equals(datacenter.getAttributeValue("id"))) {
					datacenter.setAttribute("name", name);
					datacenter.setAttribute("dbname", dbname);
					datacenter.setAttribute("dbtype", dbtype);
					if ("sqlserver".equals(dbtype)) {
						datacenter.setAttribute("dbversion", "JTDS");
					} else if ("oracle".equals(dbtype)) {
						datacenter.setAttribute("dbversion", "ORACLE");
					}
					datacenter.setAttribute("datasource", datasource);
					datacenter.setAttribute("dbuser", dbuser);
					
					datacenter.setAttribute("dbpassword", dbpassword);
					datacenter.setAttribute("maindir", maindir);
					//通过jdbc.properties来判断，是否已经正在使用
					break;
				}
			}

			XMLOutputter outp1 = new XMLOutputter();
			Format format = Format.getPrettyFormat();
			format.setEncoding("UTF-8");
			outp1.setFormat(format);
			outp1.output(dcdoc, new FileOutputStream(datacenterFile));					
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}		
				
	} else if ("edit".equals(action)) {
		//取出需要编辑的数据中心
		id = request.getParameter("id");
		
		String xmlFile = System.getProperty("oa_application.config") + File.separator + "datacenter.xml";
		File file = new File(xmlFile);
		if (file.exists()) {
			SAXBuilder builder = new SAXBuilder();
			Document doc;
			try {
				doc = builder.build(file);
				Element datacenters = doc.getRootElement();
				List datacenterList = datacenters.getChildren("datacenter");
				for (int i=0; i<datacenterList.size(); i++) {
					Element datacenter = (Element)datacenterList.get(i);
					if (id.equals(datacenter.getAttributeValue("id"))) {
						name = datacenter.getAttributeValue("name");
						if (name == null) name = "";
						dbname = datacenter.getAttributeValue("dbname");
						if (dbname == null) dbname ="";
						dbtype = datacenter.getAttributeValue("dbtype");
						if (dbtype == null) dbtype = "";
						datasource = datacenter.getAttributeValue("datasource");
						if (datasource == null) datasource = "";
						dbuser = datacenter.getAttributeValue("dbuser");
						if (dbuser == null) dbuser = "";
						dbpassword = datacenter.getAttributeValue("dbpassword");
						if (dbpassword == null) dbpassword = "";
						maindir = datacenter.getAttributeValue("maindir");
						if (maindir == null) maindir = "";						
						break;
					}
				}
			} catch (JDOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}				
		}
	}

%>
<html>
<head>
<title>管理控制台 - 数据中心</title>
<%@ include file="/common/meta2.jsp"%>
<link href="../style.css" type="text/css" rel=stylesheet>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<% if ("save".equals(action) || "update".equals(action)) { %>
<table width="100%">
  <tr>
    <td>
<% if (error_code == 1) { %>    
    数据源定义已经存在应用服务器数据源定义中，<a href="index.jsp">点这里返回数据中心列表</a>页面，使用导入功能，然后进行修改！


<% } else if (error_code == 2) { %>
    应用服务器的配置文件不存在，请确认OA的启动方式，<a href="index.jsp">点这里返回数据中心列表</a>页面
<% } else { %>
	数据中心保存成功！如果希望新的数据中心有效，必须重新启动应用服务器！<a href="index.jsp">点这里返回数据中心列表</a>
<% } %>
    </td>
  </tr>
</table>
<% } else if ("new".equals(action) || "edit".equals(action)) { %>
<script language="javascript" type="text/javascript">
function checkdata() {
	if (document.forms.registerForm.id.value == "") {
		alert("数据中心编码必须填写！");
		return false;
	}
	if (document.forms.registerForm.name.value == "") {
		alert("数据中心名称必须填写！");
		return false;
	}	
	if (document.forms.registerForm.dbname.value == "") {
		alert("数据库名称必须填写！");
		return false;
	}	
	if (document.forms.registerForm.datasource.value == "") {
		alert("数据库地址必须填写！");
		return false;
	}
	if (document.forms.registerForm.dbuser.value == "") {
		alert("数据库用户必须填写！");
		return false;
	}
	if (document.forms.registerForm.maindir.value == "") {
		alert("数据路径必须填写！");
		return false;
	}
	if (confirm("请再次确认填写的信息都正确！是否继续？")) {
		return true;
	} else {
		return false;
	}		
}
</script>
<form name="registerForm" action="register.jsp" method="post">
<input type="hidden" name="action" value="<%="new".equals(action)?"save":"update" %>">
<table width="100%">
  <tr>
  	<td width="100%">
  	  <input type="button" name="register" 
  	    value="&nbsp;保&nbsp;&nbsp;存&nbsp;"
  	    onClick="if (checkdata()) { this.form.submit(); } else { return false; }">
  	  <input type="reset" name="reset" 
  	    value="&nbsp;重&nbsp;&nbsp;置&nbsp;">
  	  <input type="button" name="returnback" 
  	    value="&nbsp;返&nbsp;&nbsp;回&nbsp;"
  	    onClick="location='index.jsp';">  	    
  	</td>
  </tr>
  <tr>
    <td>数据中心注册，是将已经存在的OA数据库或者EAS数据库注册到管理控制台，为下一步管理控制台更好的对数据库进行管理提供一个入口！</td>
  </tr>
  <tr>
    <td width="100%">
      <table width="100%" border=1>
        <tr>
          <td bgcolor="#FFCCFF" width="15%">数据中心编码</td>
          <td width="35%"><input type="text" name="id" maxlength="20" size="20" value="<%=id %>" <%="edit".equals(action)?"readonly":"" %>><SPAN class=required>×</SPAN></td>
          <td widht="50%">由英文字母和数字组成，开头必须为英文，不能与已经定义的编码名称重复，如果是EAS数据源，最好以EAS开头好进行分别</td>
        </tr>
        <tr>
          <td bgcolor="#FFCCFF">数据中心名称</td>
          <td><input type="text" name="name" value="<%=name %>"><SPAN class=required>×</SPAN></td>
          <td>数据中心的中文名称</td>
        </tr>
        <tr>
          <td bgcolor="#FFCCFF">数据库类型</td>
          <td>
          	<select name="dbtype" size=1>
          		<option value="sqlserver" <%="sqlserver".equals(dbtype)?"seleted":"" %>>SQL Server</option>
          		<option value="oracle" <%="oracle".equals(dbtype)?"seleted":"" %>>Oracle</option>
          	</select>
          </td>
          <td>选择数据中心的数据库类型</td>
        </tr>        
        <tr>
          <td bgcolor="#FFCCFF">数据库名称</td>
          <td><input type="text" name="dbname" maxlength="50" value="<%=dbname %>"><SPAN class=required>×</SPAN></td>
          <td>对应的数据库中的名称，SQL Server为数据库名，ORACLE为数据库的SID或者服务名</td>
        </tr>
        <tr>
          <td bgcolor="#FFCCFF">数据库地址</td>
          <td><input type="text" name="datasource" size="30" value="<%=datasource %>"><SPAN class=required>×</SPAN>，别忘记端口号</td>
          <td>服务器的IP地址、机器名或者域名，加上端口号，一般SQL Server的端口为1433，ORACLE的端口为1521，例如：192.168.1.124:1433</td>
        </tr>
        <tr>
          <td bgcolor="#FFCCFF">数据库用户</td>
          <td><input type="text" name="dbuser" value="<%=dbuser %>"><SPAN class=required>×</SPAN></td>
          <td>连接数据库的用户帐号</td>
        </tr>
        <tr>
          <td bgcolor="#FFCCFF">数据库密码</td>
          <td><input type="text" name="dbpassword" value="<%=dbpassword %>"><SPAN class=required>×</SPAN></td>
          <td>连接数据库的用户密码，如果没有密码可以不输</td>
        </tr>        
        <tr>
          <td bgcolor="#FFCCFF">数据路径</td>
          <td><input type="text" name="maindir" maxlength="200" size="50" value="<%=maindir %>"><SPAN class=required>×</SPAN></td>
          <td>在应用服务器，设置OA的文件所存放的位置，目录的分隔符号为/，例如C:/kingdee/data，目录最后不要写/，如果此数据源只是用于EAS数据源，那么此处就填写一个/就可以了</td>
        </tr>
      </table>
    </td>
  </tr>
  <tr>
    <td><SPAN class=required>×</SPAN>必须填写</td>
  </tr>  
</table>
</form>
<% } %>
</body>
</html>
